package com.nicedistractions.roadtriptracker;

import java.io.IOException;
import java.util.Calendar;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class Control extends Activity implements OnClickListener, OnSeekBarChangeListener{

	@SuppressWarnings("unused")
	private static final String TAG = "Control";
	private ToggleButton togglebutton;
	private Button uploadAll;
	private static TextView lastUploadValue, lastUpdateValue, latValue, longValue, accValue, bearValue, updateTimeValue, updateDistanceValue, speedValue, altValue, toUploadValue;
	private static SeekBar timeUpdateSeek, distanceUpdateSeek;
	private Intent svc;
	private int timeBetweenUpdates, distanceBetweenUpdates;
	private DBHelper db = new DBHelper(this);	

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.control);

		svc = new Intent(this, TrackerService.class);

		togglebutton = (ToggleButton) findViewById(R.id.toggleButton1);
		togglebutton.setOnClickListener(this);
		
		uploadAll = (Button) findViewById(R.id.uploadAll);
		uploadAll.setOnClickListener(this);

		lastUploadValue = (TextView) findViewById(R.id.last_upload_value);       
		lastUpdateValue = (TextView) findViewById(R.id.last_update_value); 
		latValue = (TextView) findViewById(R.id.lat_value); 
		longValue = (TextView) findViewById(R.id.long_value); 
		accValue = (TextView) findViewById(R.id.acc_value); 
		bearValue = (TextView) findViewById(R.id.bear_value); 
		updateTimeValue = (TextView) findViewById(R.id.update_time_value);
		updateDistanceValue = (TextView) findViewById(R.id.update_distance_value);
		speedValue = (TextView) findViewById(R.id.speed_value);
		altValue = (TextView) findViewById(R.id.alt_value);
		toUploadValue = (TextView) findViewById(R.id.toUpload_value);		

		timeUpdateSeek = (SeekBar)findViewById(R.id.time_update_seekbar);
		timeUpdateSeek.setOnSeekBarChangeListener(this);
		distanceUpdateSeek = (SeekBar)findViewById(R.id.distance_update_seekbar);
		distanceUpdateSeek.setOnSeekBarChangeListener(this);
		
		db.open();
		
		//If the service is running, enable the toggle button.
		if(TrackerService.running) {
			togglebutton.toggle();
			timeBetweenUpdates = TrackerService.TIME;
			distanceBetweenUpdates = TrackerService.DISTANCE;
		}
		else {
			//Default values
			timeBetweenUpdates = 60 * 60 * 1000;
			distanceBetweenUpdates = 16000;
		}
		
		timeUpdateSeek.setProgress(timeBetweenUpdates/1000/60/10);
		updateTimeValue.setText(timeBetweenUpdates/1000/60 + " Minutes");
		
		distanceUpdateSeek.setProgress(distanceBetweenUpdates/200);
		updateDistanceValue.setText(distanceBetweenUpdates + " Metres");
		
		Cursor toUploadCursor = db.getLocationsToUpload();
		startManagingCursor(toUploadCursor);
		toUploadValue.setText(toUploadCursor.getCount() + " location updates.");
	}

	public void onClick(View v) {    	
		switch (v.getId()) {		
		case (R.id.toggleButton1):			
			if (togglebutton.isChecked()) {
				//Turn tracker on						
				startService();			
			} else {
				//Turn tracker off	     
				this.stopService(svc);
			}
		break;
		case (R.id.uploadAll):			
			try {
				Uploader.uploadAll(db);
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
		break;
		}
	}

	public static void updateValues(long uploaded, long updated, double latitude, double longitude, float accuracy, float bearing, float speed, double alt) {

		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(updated);   

		lastUploadValue.setText("STUB");
		lastUpdateValue.setText(cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND));
		latValue.setText(String.valueOf(latitude));
		longValue.setText(String.valueOf(longitude));
		accValue.setText(String.valueOf(accuracy)+"m");
		bearValue.setText(String.valueOf(bearing));    	
		speedValue.setText(String.valueOf(speed));  
		altValue.setText(String.valueOf(alt));  
	}
	
	public static void updateLastUpload(long upload) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(upload); 
		lastUploadValue.setText(cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND));
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean tracking) {
		switch (seekBar.getId()) {
		case (R.id.time_update_seekbar):
			timeBetweenUpdates = progress * 10 * 60 * 1000;
			updateTimeValue.setText(String.valueOf(timeBetweenUpdates/1000/60) + " Minutes");
			break;
		case (R.id.distance_update_seekbar):
			distanceBetweenUpdates = progress * 1600;
			updateDistanceValue.setText(String.valueOf(distanceBetweenUpdates) + " Metres");
			break;
		}		

		//Do we need to restart the service?
		if (togglebutton.isChecked()) {
			restartService();
		}		
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
	}
	
	private void startService() {
		svc.putExtra("timeBetweenUpdates", timeBetweenUpdates);
		svc.putExtra("distanceBetweenUpdates", distanceBetweenUpdates);
		this.startService(svc);	
	}

	private void restartService() {		
		this.stopService(svc);
		startService();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		db.close();
	}
}